package com.logos.ruralrevitalization.service.impl;

import com.alibaba.fastjson.JSON;
import com.logos.ruralrevitalization.constant.RedisConstant;
import com.logos.ruralrevitalization.converter.AgriculturalProductConverter;
import com.logos.ruralrevitalization.entity.AgriculturalProduct;
import com.logos.ruralrevitalization.enums.IsDeleteFlagEnum;
import com.logos.ruralrevitalization.mapper.AgriculturalProductMapper;
import com.logos.ruralrevitalization.redis.RedisUtil;
import com.logos.ruralrevitalization.req.AgriculturalProductReq;
import com.logos.ruralrevitalization.resp.AgriculturalProductResp;
import com.logos.ruralrevitalization.service.AgriculturalProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 农产品表(AgriculturalProduct)表服务实现类
 *
 * @author rose
 * @since 2025-03-25 12:27:49
 */
@Service("agriculturalProductService")
@Slf4j
public class AgriculturalProductServiceImpl implements AgriculturalProductService {
    @Resource
    private AgriculturalProductMapper agriculturalProductMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     */
    @Override
    public AgriculturalProductResp queryById(Long id) {
        AgriculturalProduct agriculturalProduct = this.agriculturalProductMapper.queryById(id);
        if (agriculturalProduct == null) {
            return null;
        }
        AgriculturalProductResp agriculturalProductResp = AgriculturalProductConverter.INSTANCE.convertEntityToResp(agriculturalProduct);
        return agriculturalProductResp;
    }


    /**
     * 新增数据
     */
    @Override
    public AgriculturalProduct insert(AgriculturalProduct agriculturalProduct) {
        this.agriculturalProductMapper.insert(agriculturalProduct);
        return agriculturalProduct;
    }

    /**
     * 修改数据
     */
    @Override
    public AgriculturalProduct update(AgriculturalProduct agriculturalProduct) {
        this.agriculturalProductMapper.update(agriculturalProduct);
        agriculturalProduct = this.agriculturalProductMapper.queryById(agriculturalProduct.getId());
        if (agriculturalProduct == null) {
            return null;
        }
        return agriculturalProduct;
    }

    /**
     * 通过主键删除数据
     */
    @Override
    public boolean deleteById(Long id) {
        return this.agriculturalProductMapper.deleteById(id) > 0;
    }

    /**
     * 根据产品类型查询
     */
    @Override
    public List<AgriculturalProductResp> queryByProductType(AgriculturalProductReq agriculturalProductReq) {
        AgriculturalProduct agriculturalProduct = AgriculturalProductConverter.INSTANCE.convertReqToEntity(agriculturalProductReq);
        // 拿到当前页码和每页显示条数
        int pageNo = agriculturalProductReq.getPageNo();
        int pageSize = agriculturalProductReq.getPageSize();
        log.info("agriculturalProductReq:{}", agriculturalProductReq);
        // 判断是否是销量优先或者价格优先
        Map<String, String> sortMap = new HashMap<>();
        if (agriculturalProductReq.getIsPrice() != null && agriculturalProductReq.getIsPrice()) {
            sortMap.put("price", "asc");
        } else if (agriculturalProductReq.getIsHot() != null && agriculturalProductReq.getIsHot()) {
            sortMap.put("sales_volume", "desc");
        }
        List<AgriculturalProduct> agriculturalProducts = agriculturalProductMapper.queryAllByLimit(agriculturalProduct, pageNo, pageSize, sortMap);
        if (agriculturalProducts == null || agriculturalProducts.size() == 0) {
            return null;
        }
        List<AgriculturalProductResp> agriculturalProductRespList = new LinkedList<>();
        for (AgriculturalProduct product : agriculturalProducts) {
            AgriculturalProductResp agriculturalProductResp = AgriculturalProductConverter.INSTANCE.convertEntityToResp(product);
            agriculturalProductRespList.add(agriculturalProductResp);
        }
        return agriculturalProductRespList;
    }


    /**
     * 查询农产品销量排行榜
     */
    @Override
    public List<AgriculturalProductResp> queryHotSales() {
        // 判断缓存中是否存在数据
        if (redisUtil.exist(RedisConstant.PRODUCT_HOT_RANK)) {
            String jsonStr = redisUtil.get(RedisConstant.PRODUCT_HOT_RANK);
            List<AgriculturalProductResp> result = JSON.parseArray(jsonStr, AgriculturalProductResp.class);
            return result;
        }
        List<AgriculturalProductResp> result = agriculturalProductMapper.queryHotRank();
        if (result != null && result.size() > 0) {
            redisUtil.setNx(RedisConstant.PRODUCT_HOT_RANK, JSON.toJSONString(result), 2L, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public List<AgriculturalProductResp> search(AgriculturalProductReq agriculturalProductReq) {
        String keyWord = agriculturalProductReq.getSearchKey();
        if (keyWord == null || keyWord.trim().length() == 0) {
            return null;
        }
        List<AgriculturalProduct> agriculturalProductList = agriculturalProductMapper.search(keyWord);
        List<AgriculturalProductResp> result = new LinkedList<>();
        agriculturalProductList.forEach(item -> {
            AgriculturalProductResp agriculturalProductResp = AgriculturalProductConverter.INSTANCE.convertEntityToResp(item);
            result.add(agriculturalProductResp);
        });
        return result;
    }

    @Override
    public List<AgriculturalProductResp> queryRuralProd(Long userId) {
        AgriculturalProduct agriculturalProduct = new AgriculturalProduct();
        agriculturalProduct.setSupplierId(userId);
        agriculturalProduct.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<AgriculturalProduct> agriculturalProductList = agriculturalProductMapper.queryByCondition(agriculturalProduct);
        if (agriculturalProductList == null || agriculturalProductList.size() == 0) {
            return null;
        }
        List<AgriculturalProductResp> result = new LinkedList<>();
        agriculturalProductList.forEach(item -> {
            AgriculturalProductResp agriculturalProductResp = AgriculturalProductConverter.INSTANCE.convertEntityToResp(item);
            result.add(agriculturalProductResp);
        });
        return result;
    }

    @Override
    public Boolean add(AgriculturalProductReq agriculturalProductReq) {
        AgriculturalProduct agriculturalProduct = AgriculturalProductConverter.INSTANCE.convertReqToEntity(agriculturalProductReq);
        agriculturalProduct.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        agriculturalProduct.setSalesVolume(0);
        return this.agriculturalProductMapper.insert(agriculturalProduct) > 0;
    }

    @Override
    public Boolean down(AgriculturalProductReq agriculturalProductReq) {
        // 下架农产品
        AgriculturalProduct agriculturalProduct = AgriculturalProductConverter.INSTANCE.convertReqToEntity(agriculturalProductReq);
        agriculturalProduct.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode());
        return agriculturalProductMapper.update(agriculturalProduct) > 0;
    }

    @Override
    public Boolean updateInfo(AgriculturalProductReq agriculturalProductReq) {
        // 更新农产品信息
        AgriculturalProduct agriculturalProduct = AgriculturalProductConverter.INSTANCE.convertReqToEntity(agriculturalProductReq);
        return agriculturalProductMapper.update(agriculturalProduct) > 0;
    }

    @Override
    public List<AgriculturalProductResp> showHome() {
        //  查看redis中是否存在
        if (redisUtil.exist(RedisConstant.PRODUCT_HOME)) {
            String jsonStr = redisUtil.get(RedisConstant.PRODUCT_HOME);
            List<AgriculturalProductResp> result = JSON.parseArray(jsonStr, AgriculturalProductResp.class);
            return result;
        }
        List<AgriculturalProduct> agriculturalProductList = agriculturalProductMapper.showHome();
        List<AgriculturalProductResp> result = new LinkedList<>();
        if (agriculturalProductList != null && agriculturalProductList.size() > 0) {
            agriculturalProductList.forEach(item -> {
                AgriculturalProductResp agriculturalProductResp = AgriculturalProductConverter.INSTANCE.convertEntityToResp(item);
                result.add(agriculturalProductResp);
            });
            redisUtil.setNx(RedisConstant.PRODUCT_HOME, JSON.toJSONString(result), 2L, TimeUnit.MINUTES);
        }
        return result;
    }


}
